module App
    class Watchdog < Timer
        signals 'screenSaverActivated(QObject*)'
        signals 'screenSaverDeactivated(QObject*, QDateTime*)'
        signals 'old_task_detected(QObject*)'
        signals 'recent_task_detected(QObject*)'
        signals 'taskStopped()'
        signals 'taskRunning(QObject*, int)'
        
        def initialize(toggl_tree_model)
            # XXX memory leak in QtRuby..?
            super(1 * 1000)
            @toggl_tree_model = toggl_tree_model
            @lastidle = false
            @lastrunningtask = false
            @ticker = 0
        end
        
        def colorize_tasks()
            @toggl_tree_model.eachTask { |task|
                #p "doing #{task.description}"
                if task.stop_ms == 0
                    # Lehet erre semmi szukseg, legyen egyenrangu az ujrainditott
                    # friss task -al.
                    #p "running: #{task.description}"
                    #task.setForeground(Qt::Brush.new(Qt::Color.new(Qt::yellow)))
                elsif task.stop_ms/1000 < Time.now.to_i - 60*60
                    #p "oldie: #{task.description} #{task.stop_ms}"
                    #task.setForeground(Qt::Brush.new(Qt::Color.new(Qt::gray)))
                    emit old_task_detected(task)
                else
                    #p "newie: #{task.description} #{task.stop_ms}"
                    #task.setForeground(Qt::Brush.new(Qt::Color.new(Qt::white)))
                    emit recent_task_detected(task)
                end
            }
        end

        private
        def timeout()
            runningtask = @toggl_tree_model.getRunningTask

            if runningtask
                runningtask.updateChildItem
                emit taskRunning(runningtask, @ticker += 1)
            else
                emit taskStopped()
                @ticker = 0
            end

            colorize_tasks

            screensaver = Qt::DBusInterface.new("org.freedesktop.ScreenSaver", "/ScreenSaver",
                "org.freedesktop.ScreenSaver", Qt::DBusConnection.sessionBus)
            unless screensaver.valid?
                App::View::ErrorDialog.new $widget.view, "org.freedesktop.ScreenSaver not valid"
                exit 0
            end
            idle = screensaver.GetActive
            #p idle.inspect
            if runningtask and idle and not @lastidle
                @lastrunningtask = runningtask
                @idlesince = Time.now
                emit screenSaverActivated(runningtask)
            end
            if @lastrunningtask and not idle and @lastidle
                emit screenSaverDeactivated(@lastrunningtask, @idlesince.to_date_time)
                @lastrunningtask = false
            end
            @lastidle = idle
        end
    end
end
